<template>
  <div id="app">
    <el-row :gutter="20">
      <el-col :span="24" :offset="0" class="header">
        <upload-excel-component
          style="margin-top: 15px;margin-left:15px;display: inline-block;"
          :on-success="handleSuccess"
          :before-upload="beforeUpload" />
        <el-select
          placeholder="选择坐标类型"
          style="margin-left: 15px" v-model="coord_type" filterable>
          <el-option v-for="item in coord_types"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button
          type="primary"
          size="default"
          class="trans"
          :loading="isLoading"
          @click="start">开始转换
        </el-button>
        <el-button :loading="isLoading"
        type="primary" size="default"
        class="export" @click="handleDownload">导出表格</el-button>
        <el-button @click="downloadDemo">下载模板</el-button>
     </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 15px; text-align:left">
      <el-col :span="24" :offset="0">
        自定义公式：
        <el-input v-model="evalString" style="width: 500px" placeholder="自定义公式" size="normal" clearable></el-input>
        <el-input style="width: 500px; margin-left: 15px" v-model="AK" placeholder="如果你有百度地图的AK码，在这里输入" size="normal" clearable></el-input>
      </el-col>
      <el-col :span="12" :offset="0">

      </el-col>
    </el-row>
    <!-- {{message.distance}}米，{{message.duration}}秒 -->
    <el-row :gutter="20">
      <el-col :span="24" :offset="0">
        <el-table style="margin-top: 15px" :data="tableData" border stripe height="500">
          <el-table-column
            prop="origin"
            label="起点"
            :min-width="100">
          </el-table-column>
          <el-table-column
            prop="destination"
            label="终点"
            :min-width="100">
          </el-table-column>
          <el-table-column
            label="结果"
            :min-width="50">
            <template slot-scope="scope">
              {{ scope.row.ok || '否' }}
            </template>
          </el-table-column>
           <el-table-column
            label="接口返回值"
            :min-width="100">
            <template slot-scope="scope">
              {{ scope.row.tip || '待转换' }}
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24" :offset="0">
        <p>先上传excel文件，选择文件中坐标的类型，点击转换，完成后再导出</p>
        <p>如果出现卡主不动的情况，刷新页面</p>
        <p>免费api的配额是每天2000条，一直失败那估计就是配额用光了</p>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import * as $ from 'axios'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
export default {
  name: 'app',
  components: { UploadExcelComponent },
  data () {
    return {
      message: {
        distance: 0,
        duration: 0
      },
      tableData: [],
      isLoading: false,
      coord_type: 'wgs84',
      evalString: '%distance% < 1000 && %duration% < 15 * 60',
      AK: '',
      coord_types: [
        {
          label: 'gps设备获取的坐标',
          value: 'wgs84'
        },
        {
          label: '国测局加密坐标',
          value: 'gcj02'
        },
        {
          label: '百度墨卡托坐标',
          value: 'bd09mc'
        },
        {
          label: '百度经纬度坐标',
          value: 'bd09ll'
        }
      ]
    }
  },
  async mounted () {
    // console.log('123')
    // const data = await this.getDriving('40.056878,116.30815', '40.056878,118.31818')
    // this.message = data[0]
  },
  methods: {
    downloadDemo () {
      window.open('http://www.miyaomiya.com/file/bdmap/demo/distance_judgment.xlsx')
    },
    handleDownload () {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['起点', '终点', '结果', '接口返回值']
        const list = this.tableData
        const data = []
        for (const key in list) {
          const element = list[key]
          const row = []
          row.push(element.origin || '')
          row.push(element.destination || '')
          row.push(element.ok || '否')
          row.push(element.tip || '')
          data.push(row)
        }
        // const data = this.formatJson(filterVal, list)
        // console.log(data)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'download',
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    async start () {
      for (const key in this.tableData) {
        const element = this.tableData[key]
        try {
          if (element.origin && element.destination) {
            const data = await this.getDriving(element.origin, element.destination)
            if (data.status === 0) {
              const route = data.result.routes[0]
              // distance duration
              const evalString = this.evalString.replace('%distance%', route.distance)
                .replace('%duration%', route.duration)

              // eslint-disable-next-line no-eval
              if (eval(evalString)) {
                this.$set(element, 'ok', '是')
              } else {
                this.$set(element, 'ok', '否')
              }
              this.$set(element, 'tip', `distance:${route.distance}m,duration:${route.duration}s`)
            } else {
              this.$set(element, 'ok', '否')
              this.$set(element, 'tip', data.message)
            }
          } else {
            this.$set(element, 'ok', '否')
            this.$set(element, 'tip', 'Missing parameter')
          }
        } catch (e) {
          this.$set(element, 'ok', '否')
          this.$set(element, 'tip', JSON.stringify(e))
        }
      }
    },
    beforeUpload (file) {
      const isLt1M = file.size / 1024 / 1024 < 5
      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess ({ results, header }) {
      // console.log(results)
      // console.log(header)
      this.tableData = results
      // this.tableHeader = header
    },
    async getDriving (origin, destination) {
      try {
        this.isLoading = true
        const { data } = await $.get(`http://api.miyaomiya.com:12450/api/v1/bdmap/driving?origin=${origin}&destination=${destination}&coord_type=${this.coord_type}&AK=${this.AK || ''}`)
        // console.log(data)
        return data
      } catch (e) {
        return e
      } finally {
        this.isLoading = false
      }
      // origin = Number(origin).toFixed(6)
      // destination = Number(destination).toFixed(6)
    }
  }
}
</script>

<style  lang="scss">
body,html {
  margin: 0;
  padding: 0;
  #app {
    padding: 15px;
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    .header {
      display: flex;
      align-items: flex-end;
      .trans {
        margin-left: 15px;
      }
    }
    // margin-top: 60px;
  }
}
</style>
